package com.ljh.order.service;

import com.ljh.order.mapper.OrderInfoMapper;
import com.ljh.order.model.OrderInfo;
import com.ljh.order.model.ProductInfo;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author: Themberfue
 * @date: 2025/4/10 19:10
 * @description:
 */
@Slf4j
@Service
public class OrderService {
    @Autowired
    OrderInfoMapper orderInfoMapper;

    @Autowired
    RestTemplate restTemplate;

    public OrderInfo getOrderById(Integer orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectOrderById(orderId);
        // TODO 使用 SpringCloud Load Balance
        // TODO 拼接 url
        String url = "http://product-service/product/" + orderInfo.getProductId();
        log.info("远程调用地址：{}", url);
        ProductInfo productInfo = restTemplate.getForObject(url, ProductInfo.class);
        orderInfo.setProductInfo(productInfo);
        return orderInfo;
    }


//    @Autowired
//    DiscoveryClient discoveryClient;
//
//    private AtomicInteger requestCount = new AtomicInteger(1);
//
//    List<ServiceInstance> instances;
//    @PostConstruct
//    void init() {
//        instances = discoveryClient.getInstances("product-service");
//    }
//
//    public OrderInfo getOrderById(Integer orderId) {
//        OrderInfo orderInfo = orderInfoMapper.selectOrderById(orderId);
//
//        // TODO 获取分配给当前请求的实例索引
//        int index = requestCount.getAndIncrement() % instances.size();
//
//        // TODO 获取示例 uri
//        String uri = instances.get(index).getUri().toString();
//
//        // TODO 拼接 url
//        String url = uri + "/product/" + orderInfo.getProductId();
//
//        log.info("远程调用地址：{}", url);
//        ProductInfo productInfo = restTemplate.getForObject(url, ProductInfo.class);
//        orderInfo.setProductInfo(productInfo);
//        return orderInfo;
//    }

//    public OrderInfo getOrderById(Integer orderId) {
//        OrderInfo orderInfo = orderInfoMapper.selectOrderById(orderId);
//
//        List<ServiceInstance> instances = discoveryClient.getInstances("product-service");
//        String uri = instances.get(0).getUri().toString();
//        String url = uri + "/product/" + orderInfo.getProductId();
//        log.info("远程调用地址：{}", url);
//        ProductInfo productInfo = restTemplate.getForObject(url, ProductInfo.class);
//        orderInfo.setProductInfo(productInfo);
//        return orderInfo;
//    }
}
